<template>
	<div class="app-container">
		<el-form :inline="true" label-width="120px">
			<el-form-item label="活动创建时间">
				<el-date-picker v-model="timeValue" type="datetimerange" :picker-options="pickerOptions"
					range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" align="right"
					value-format="yyyy-MM-dd HH:mm:ss">
				</el-date-picker>
			</el-form-item>
			<el-form-item label="片区名称">
				<el-input placeholder="请输入片区名称" v-model="queryParams.areaName"></el-input>
			</el-form-item>
			<el-form-item label="活动名称">
				<el-input placeholder="请输入片区名称" v-model="queryParams.activityName"></el-input>
			</el-form-item>
			<el-form-item label="活动类目">
				<el-select v-model="queryParams.activityClassification" clearable>
					<el-option v-for="i in activityOptions" :key="i.createTime" :value="i.dictValue"
						:label="i.dictLabel"></el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="审核状态">
				<el-select v-model="queryParams.status" clearable>
					<el-option v-for="i in statusLabel" :key="i.dictValue" :value="i.dictValue"
						:label="i.dictLabel"></el-option>
				</el-select>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" icon="el-icon-search" size="mini" @click="serachFn">搜索</el-button>
				<el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
				<el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
					v-hasPermi="['monitor:job:export']">导出</el-button>
			</el-form-item>
		</el-form>
		<el-table v-loading="loading" :data="list">
			<el-table-column type="index"></el-table-column>
			<el-table-column prop="areaName" label="片区名称"></el-table-column>
			<el-table-column prop="createTime" label="积分申报时间"></el-table-column>
			<el-table-column prop="activeJoinTime" label="活动时间"></el-table-column>
			<el-table-column prop="userNickName" label="用户昵称"></el-table-column>
			<el-table-column label="活动类目">
				<template slot-scope="scope">
					<span>{{ activityClassName(scope.row.activityClassification) }}</span>
				</template>
			</el-table-column>
			<el-table-column prop="activityName" label="活动名称"> </el-table-column>
			<el-table-column prop="activeCreateTime" label="活动创建时间"></el-table-column>
			<el-table-column prop="status" label="状态">
				<template slot-scope="scope">
					<el-tag :type="statusTag[scope.row.status]">
						{{
              scope.row.status == 0
                ? "待审核"
                : scope.row.status == 1
                ? "通过"
                : "驳回"
            }}
					</el-tag>
				</template>
			</el-table-column>
			<el-table-column prop="declarationDescribe" label="申报描述">
			</el-table-column>
			<el-table-column prop="rewardPoints" label="申报积分"> </el-table-column>
			<el-table-column prop="rejectReason" label="备注">
				<template slot-scope="scope" v-if="scope.row.status == 2">
					<span>驳回理由：{{ scope.row.rejectReason }}</span></template>
			</el-table-column>
			<el-table-column label="操作">
				<template slot-scope="scope">
					<el-button size="mini" type="text" icon="el-icon-edit"
						@click="handleDetail(scope.row)">附件查看</el-button>
					<el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
						v-hasPermi="['system:user:remove']">删除</el-button>
					<el-button v-if="scope.row.status == 0" size="mini" type="text" icon="el-icon-success"
						@click="handlePass(scope.row, 1)">审核通过</el-button>
					<el-button v-if="scope.row.status == 0" size="mini" type="text" icon="el-icon-error"
						@click="handlePass(scope.row, 2)">审核驳回</el-button>
				</template>
			</el-table-column>
		</el-table>
		<pagination :total="total" :page.sync="queryParams.params.pageNum" :limit.sync="queryParams.params.pageSize"
			@pagination="getList" />
		<el-dialog title="附件信息" :visible.sync="dialogDetail" width="500px">
			<ul class="file-list-dialog">
				<li v-for="(file, index) in processDetail" :key="index">
					<div class="file-name"><i class="el-icon-s-order" />{{ file.fileNames }}</div>
					<div class="file-tag">
						<el-button type="success" size="mini" :loading="file.loadingBtn"
							@click="preview(file)">预览</el-button>
						<el-button type="primary" size="mini" @click="downloadFn(file)">下载</el-button>
					</div>
				</li>
			</ul>
			<span slot="footer" class="dialog-footer">
				<el-button type="primary" @click="dialogDetail = false">确 定</el-button>
			</span>
		</el-dialog>
		<el-dialog title="审核" :before-close="dialogHandleClose" :visible.sync="dialogStatus" width="500px">
			<el-form label-position="left" :model="toExamine" :rules="rules" ref="toExamine">
				<div v-if="toExamine.status == 1">
					<el-form-item label="该项目通过审核，请输入获得积分数！">
					</el-form-item>
					<el-form-item label="积分数" label-width="80px" prop="rewardPoints">
						<el-input v-model="toExamine.rewardPoints"></el-input>
					</el-form-item>
				</div>
				<div v-if="toExamine.status == 2">
					<el-form-item label="该项目未通过审核，请填入驳回理由！ ">
					</el-form-item>
					<el-form-item label="驳回理由:" label-width="100px" prop="rejectReason">
						<el-input v-model="toExamine.rejectReason" type="textarea" maxlength="50"
							show-word-limit></el-input>
					</el-form-item>
				</div>
			</el-form>
			<el-form v-if="toExamine.status == 2"> </el-form>
			<span slot="footer" class="dialog-footer">
				<el-button type="primary" @click="dialogHandleClose()">取消</el-button>
				<el-button type="primary" @click="submitForm('toExamine')">确 定</el-button>
			</span>
		</el-dialog>
	</div>
</template>
<script>
	import {
		listData
	} from "@/api/system/dict/data";
	import {
		batchDelete,
		integralDetailApi,
		integralAuditApi,
		integralPreviewApi,
	} from "@/api/party/integral";
	export default {
		data() {
			var checkPoints = (rule, value, callback) => {
				if (!value) {
					return callback(new Error("积分数不能为空"));
				}
				if (/^[1-9]\d*$/.test(value)) {
					if (value > this.toExamine.defaultRewardPoints) {
						callback(
							new Error(
								"该活动设置积分最大值为" + this.toExamine.defaultRewardPoints
							)
						);
					} else {
						callback();
					}
				} else {
					return callback(new Error("积分必须大于0且为整数！"));
				}
			};
			return {
				toExamine: {
					id: "",
					defaultRewardPoints: null,
					status: null,
					rejectReason: "",
					rewardPoints: "",
					belongToArea: null
				},
				processDetail: null,
				//审核状态（0待审核 1通过 2驳回）
				statusLabel: [{
						dictLabel: "待审核",
						dictValue: "0",
					},
					{
						dictLabel: "通过",
						dictValue: "1",
					},
					{
						dictLabel: "拒绝",
						dictValue: "2",
					},
				],
				statusTag: {
					0: "warning",
					1: "success",
					2: "danger",
				},
				dialogDetail: false,
				dialogStatus: false,

				activityOptions: [],
				loading: false,
				list: [],
				total: 0,
				pickerOptions: {
					shortcuts: [{
							text: "最近一周",
							onClick(picker) {
								const end = new Date();
								const start = new Date();
								start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
								picker.$emit("pick", [start, end]);
							},
						},
						{
							text: "最近一个月",
							onClick(picker) {
								const end = new Date();
								const start = new Date();
								start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
								picker.$emit("pick", [start, end]);
							},
						},
						{
							text: "最近三个月",
							onClick(picker) {
								const end = new Date();
								const start = new Date();
								start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
								picker.$emit("pick", [start, end]);
							},
						},
					],
				},
				timeValue: "",
				queryParams: {
					status: "",
					activityClassification: "",
					areaName: "",
					activityName: "",
					params: {
						startTime: "",
						endTime: "",
						pageNum: 1,
						pageSize: 10,
					},
				},
				rules: {
					rewardPoints: [{
						validator: checkPoints,
						trigger: "blur"
					}],
					rejectReason: [{
						required: true,
						message: "请输入驳回理由",
						trigger: "blur"
					}, ],
				},
			};
		},
		watch: {
			timeValue(e) {
				this.queryParams.params.startTime = e[0];
				this.queryParams.params.endTime = e[1];
			},
		},
		computed: {
			activityClassName() {
				return (activityClassification) => {
					let dictLabel = "";
					if (this.activityOptions.length == 0) return "";
					this.activityOptions.forEach((item) => {
						if (item.dictValue == activityClassification) {
							dictLabel = item.dictLabel;
						}
					});
					return dictLabel;
				};
			},
		},
		async created() {
			await this.listDataFn();
			await this.getList();
		},
		methods: {
			/** 删除按钮操作 */
			handleDelete(row) {
				const ids = [];
				let id = row.id.toString()
				console.log(typeof id)
				ids.push(id)
				console.log(ids,row)
				this.$modal
					.confirm('是否确认删除片区名称为"' + row.areaName + '"的数据项？')
					.then(function() {
						return batchDelete(ids);
					})
					.then(() => {
						this.getList();
						this.$modal.msgSuccess("删除成功");
					})
					.catch(() => {});
			},
			submitForm(formName) {
				this.$refs[formName].validate((valid) => {
					if (valid) {
						integralAuditApi(this.toExamine).then((res) => {
							this.$modal.msgSuccess("操作成功");
							this.dialogHandleClose();
							this.getList();
						});
					} else {
						console.log("error submit!!");
						return false;
					}
				});
			},
			preview(file) {
				file.loadingBtn = true;
				//白名单
				let fileType = ["jepg", "jpg", "png", "map4", "pdf"];
				let suffix = file.fileNames.split(".")[1];
				if (fileType.includes(suffix)) {
					file.loadingBtn = false;
					window.open(process.env.VUE_APP_BASE_API + file.filePath, "_blank");
				} else {
					integralPreviewApi(file.filePath)
						.then((res) => {
							let blob = new Blob([res], {
								type: "application/pdf"
							});
							let url = window.URL.createObjectURL(blob);
							file.loadingBtn = false;
							window.open(url, "_blank");
						})
				}
			},
			downloadFn(row) {
				var name = row.fileNames.split(".")[0];
				var url = process.env.VUE_APP_BASE_API + row.filePath;
				var suffix = url.substring(url.lastIndexOf("."), url.length);
				const a = document.createElement("a");
				a.setAttribute("download", name + suffix);
				a.setAttribute("target", "_blank");
				a.setAttribute("href", url);
				a.click();
			},
			//查看附件
			handleDetail(v) {
				if (!v.fileNames) {
					return this.$message({
						message: "该申报没有附件信息！",
						type: "warning",
					});
				}
				let fileNames, filePath;
				if (v.fileNames.indexOf(",") > 0) {
					fileNames = v.fileNames.split(",");
				} else {
					fileNames = [v.fileNames];
				}
				if (v.filePath.indexOf(",") > 0) {
					filePath = v.filePath.split(",");
				} else {
					filePath = [v.filePath];
				}
				let arr = [];
				fileNames.forEach((item, index) => {
					arr.push({
						fileNames: item,
						filePath: filePath[index],
						loadingBtn: false,
					});
				});

				this.processDetail = arr;
				this.dialogDetail = true;
			},
			//通过
			handlePass(e, status) {
				this.dialogStatus = true;
				this.toExamine.rewardPoints = e.defaultRewardPoints;
				this.toExamine.id = e.id;
				this.toExamine.defaultRewardPoints = e.defaultRewardPoints;
				this.toExamine.status = status;
				this.toExamine.belongToArea = e.belongToArea;
			},
			//审核弹框关闭前回调
			dialogHandleClose() {
				this.toExamine = {
					id: "",
					defaultRewardPoints: null,
					status: null,
					rejectReason: "",
					rewardPoints: "",
					belongToArea: null
				};
				this.$refs["toExamine"].resetFields();
				this.dialogStatus = false;
			},
			//获取活动分类
			listDataFn() {
				listData({
					dictType: "activity_classification",
				}).then((res) => {
					this.activityOptions = res.rows;
				});
			},
			getList() {
				this.loading = true;
				integralDetailApi(this.queryParams)
					.then((res) => {
						this.total = res.total;
						this.list = res.rows;
					})
					.finally(() => {
						this.loading = false;
					});
			},
			serachFn() {
				this.queryParams.params.pageNum = 1;
				this.getList();
			},
			resetQuery() {
				this.queryParams = {
					status: "",
					activityClassification: "",
					areaName: "",
					activityName: "",
					params: {
						startTime: "",
						endTime: "",
						pageNum: 1,
						pageSize: 10,
					},
				};
				this.timeValue = "";
				this.getList();
			},
			/** 导出按钮操作 */
			handleExport() {
				this.download('/party/declaration/export', {
					...this.queryParams
				}, `积分申报列表${new Date().getTime()}.xlsx`)
			}
		},
	};
</script>
<style lang="scss" scoped>
	.file-list-dialog {
		padding: 0;

		li {
			display: flex;
			margin-bottom: 10px;
			align-items: center;
			justify-content: space-between;
			cursor: pointer;

			.file-name {
				flex: 1;
				overflow: hidden;
				text-overflow: ellipsis;
				white-space: nowrap;
			}

			.file-tag {
				width: 150px;
				text-align: center;

				.el-tag {
					margin-left: 10px;
				}
			}
		}
	}
</style>